package com.shao.onlinepdf.excep;

import com.shao.onlinepdf.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * @author shaohuailin
 * @date 2021/11/19
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public Result apiException(ApiException e) {
        log.warn("api exception:{}", e.getMessage());
        return e.getResult();
    }

    @ExceptionHandler(value = Exception.class)
    public Object exception(HttpServletRequest request, Exception e) {
        log.error("a exception", e);
        // 获取异常拦截器判断的类型
        Boolean isView = (Boolean) request.getAttribute("is_view");
        if (isView == null) {
            log.warn("get attribute is_view is null");
        }
        // 是返回页面模式
        if (isView != null && isView) {
            ModelAndView mav = new ModelAndView("/error");
            return mav;
        }
        // 返回json模式
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
        mav.addObject(Result.fail(e.getMessage()));
        return mav;
    }
}
